package sunyu.controller.common.property.editor;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.nutz.lang.Times;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.util.Date;

/**
 * 与spring mvc的@InitBinder结合
 * <p>
 * 转换前台的字符串格式的日期值给后台使用
 *
 * @author 孙宇
 */
public class DateTimePropertyEditorSupport extends PropertyEditorSupport {

    public DateTimePropertyEditorSupport() {
    }

    @Override
    public String getAsText() {
        Date value = (Date) getValue();
        return (value != null ? FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss").format(value) : "");
    }

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (text == null || StringUtils.isBlank(text)) {
            setValue(null);
        } else {
            try {
                setValue(Times.parse("yyyy-MM-dd HH:mm:ss", StringUtils.trim(text)));
            } catch (ParseException e) {
                try {
                    setValue(Times.parse("yyyy-MM-dd", StringUtils.trim(text)));
                } catch (ParseException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

}
